package org.xinyin025.sinaweibodemo;

import java.io.IOException;

import com.weibo.sdk.android.Oauth2AccessToken;
import com.weibo.sdk.android.WeiboException;
import com.weibo.sdk.android.api.StatusesAPI;
import com.weibo.sdk.android.net.RequestListener;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

/**
 * 发布带本地图片的微博
 * @author 蓝骑士(xinyin025)
 * @version 1.0
 */
public class SendMsgWithPic extends Activity implements View.OnClickListener,
		RequestListener {
	SharedPreferences pre;
	EditText msg_et;
	Button send_btn;
	Oauth2AccessToken access_token;
	StatusesAPI api;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_sendmsgwithpic);
		pre = getSharedPreferences("Setting", MODE_PRIVATE);
		initView();
		send_btn.setOnClickListener(this);
	}

	void initView() {
		msg_et = (EditText) findViewById(R.id.msg_et);
		send_btn = (Button) findViewById(R.id.send_btn);
	}

	@Override
	public void onComplete(String arg0) {
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				Toast.makeText(SendMsgWithPic.this, "分享成功!", Toast.LENGTH_SHORT)
						.show();
			}
		});
		SendMsgWithPic.this.finish();
	}

	@Override
	public void onError(WeiboException arg0) {
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				Toast.makeText(SendMsgWithPic.this, "分享失败!", Toast.LENGTH_SHORT)
						.show();
			}
		});
		SendMsgWithPic.this.finish();

	}

	@Override
	public void onIOException(IOException arg0) {
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				Toast.makeText(SendMsgWithPic.this, "分享失败!", Toast.LENGTH_SHORT)
						.show();
			}
		});
		SendMsgWithPic.this.finish();

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.send_btn:
			access_token = new Oauth2AccessToken(pre.getString("token", ""),
					pre.getString("expires_in", "0"));
			api = new StatusesAPI(access_token);
			String content = msg_et.getText().toString();
			if (TextUtils.isEmpty(content)) {
				Toast.makeText(SendMsgWithPic.this, "请输入发布内容！",
						Toast.LENGTH_SHORT).show();
				return;
			}
			try {
				/*
				 * 发布带本地图片微博
				 * 请先确认图片已存在
				 */
				api.upload(content, "mnt/sdcard/image.jpeg", "0", "0", this);
			} catch (Exception e) {
			}
			break;

		default:
			break;
		}
	}
}
